//
// Created by yunnan xu on 2020/12/8.
//

#include "Convex.h"
#include <vector>

namespace Phy {


    PolyConvex::PolyConvex(std::vector<glm::vec3> & origin_convex_points)
    {
        convex_points_number = origin_convex_points.size();
        origin_points.resize(convex_points_number);
        convex_points.resize(convex_points_number);

        for (int i = 0; i < convex_points_number; i++)
        {
            origin_points[i] = glm::vec4(origin_convex_points[i], 1.0f);
            convex_points[i].pos = origin_convex_points[i];
        }
    }

    const std::vector<Point> & PolyConvex::GetPoints()
    {
        return convex_points;
    }

    void PolyConvex::UpdateWithModelMatrix(glm::mat4 model_mat)
    {
        // PHYLOGI("Convex UpdateWithModelMatrix");

        for (int i = 0; i < convex_points_number; i++)
        {
            convex_points[i].pos = model_mat * origin_points[i];
        }
    }

    Point PolyConvex::GetSupport(glm::vec3 dir)
    {
        float max_proj_length = FLOAT_MINUS_MAX;
        dir = glm::normalize(dir);
        Point support{};

        for (Point p : convex_points)
        {
            float proj_length = glm::dot(p.pos, dir);
            if (proj_length > max_proj_length)
            {
                max_proj_length = proj_length;
                support = p;
            }
        }
        return support;
    }

}